﻿using System.Collections.Generic;
using GCTrackableRace.Interfaces;
using Newtonsoft.Json;
using System.IO;

namespace GcTrackableRace.Persistence.ScoreFiles
{
	public class ScoreJsonPersistence: IScorePersistance
	{
		public void PersistTrackableScores(IEnumerable<ITrackable> trackables, IProgramConfigurationSettings programConfigurationSettings)
		{
			string jsonText = JsonConvert.SerializeObject(trackables);

			PersistJsonText(jsonText, programConfigurationSettings);
		}

		private static void PersistJsonText(string jsonText, IProgramConfigurationSettings programConfigurationSettings)
		{
			var fileNameAndPath = programConfigurationSettings.GetOutputFileNameAndLocation(FileType.JsonRaceResultTextFile);

			if (File.Exists(fileNameAndPath))
				File.Delete(fileNameAndPath);

			if (!Directory.Exists(programConfigurationSettings.OutputDirectory))
				Directory.CreateDirectory(programConfigurationSettings.OutputDirectory);

			File.WriteAllText(fileNameAndPath, jsonText);
		}
	}
}